package fun.easycode.webterminal.service.impl;

import fun.easycode.webterminal.common.contract.DynamicOperate;
import fun.easycode.webterminal.common.contract.PageDTO;
import fun.easycode.webterminal.common.contract.R;
import fun.easycode.webterminal.common.datafill.DataFill;
import fun.easycode.webterminal.dao.Machine;
import fun.easycode.webterminal.dao.MachineRepository;
import fun.easycode.webterminal.service.MachineService;
import fun.easycode.webterminal.service.cmd.MachineBatchDeleteCmd;
import fun.easycode.webterminal.service.cmd.MachinePageQry;
import fun.easycode.webterminal.service.cmd.MachineSaveCmd;
import fun.easycode.webterminal.service.cmd.MachineSaveCmdAssembler;
import fun.easycode.webterminal.service.dto.MachineDTO;
import fun.easycode.webterminal.service.dto.MachineDTOAssembler;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

@Service
public class MachineServiceImpl implements MachineService {

    @Resource
    private MachineRepository machineRepository;


    @Override
    public R<MachineDTO> getById(String id) {

        Machine machine = machineRepository.getById(id);

        if(machine == null){
            return R.error("未找到该机器");
        }

        return R.success(MachineDTOAssembler.INSTANCE.to(machine));
    }

    @Override
    public R<String> delete(String id) {

        boolean r = machineRepository.removeById(id);
        return r? R.message("删除成功") : R.error("删除失败");
    }

    @Override
    public R<String> batchDelete(MachineBatchDeleteCmd cmd) {
        cmd.validate();

        boolean r = machineRepository.removeBatchByIds(cmd.getIds());

        return r ? R.message("删除成功!") : R.error("删除失败!");
    }

    public R<String> save (MachineSaveCmd cmd){
        cmd.validate();

        machineRepository.saveOrUpdate(MachineSaveCmdAssembler.INSTANCE.to(cmd));

        return R.message("保存成功!");
    }

    @DataFill
    public R<PageDTO<MachineDTO>> page(MachinePageQry cmd){
        cmd.validate();
        return R.success(DynamicOperate.page(cmd, machineRepository.getBaseMapper(), MachineDTOAssembler.INSTANCE::to));
    }
}
